package com.chap10;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created by IntelliJ IDEA.
 * User: bj910
 * Date:2023-03-29
 * Time: 4:43
 * To change this template use File | Settings | File Templates.
 */
public class BlockingQueueExample {
    public static final int QUEUE_CAPACITY = 5;
    public static final int PRODUCER_DELAY_MS = 1000;
    public static final int CONSUMER_DELAY_MS = 2000;

    public static void main(String[] args) {
        //数组实现的阻塞队列需要一个容量
        //没有无参构造器，天然就是有界队列，当然也是可以传int类型的最大值，相当于是无界
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(QUEUE_CAPACITY);
        new Thread(()->{
            while (true){
                try{
                    blockingQueue.put("producer");
                    System.out.println("生产了一个元素，队列中元素个数："+blockingQueue.size());
                    Thread.sleep(PRODUCER_DELAY_MS);
                }catch (Exception e){

                }
            }
        }).start();

        new Thread(()->{
            while (true){
                try{
                    String element = blockingQueue.take();
                    System.out.println("消费了一个元素，队列中元素个数："+blockingQueue.size());
                    Thread.sleep(CONSUMER_DELAY_MS);
                }catch (Exception e){

                }
            }
        }).start();
    }
}
